/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Clases.Consulta;
import Clases.Producto;
import Clases.Solicitud;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Ricardo
 */
public class AgregarSolicitud extends javax.swing.JFrame {

    /**
     * Creates new form AgregarSolicitud
     */
    public AgregarSolicitud() {
        initComponents();
        DefaultComboBoxModel cm = (DefaultComboBoxModel) listProductos.getModel();
        try {
            if (Consulta.getProductos() != null) {
                cm.addElement("Seleccione un Producto");
                for (Producto producto : Consulta.getProductos()) {
                    cm.addElement(producto.getDescripcionProducto());
                }
            }
        } catch (Exception e) {
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        menu_tabla = new javax.swing.JPopupMenu();
        pop_eliminar_fila = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaProductos = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        listProductos = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        btnAgregar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();

        pop_eliminar_fila.setText("Eliminar");
        pop_eliminar_fila.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pop_eliminar_filaActionPerformed(evt);
            }
        });
        menu_tabla.add(pop_eliminar_fila);
        menu_tabla.add(jSeparator1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agregar Nueva Solicitud");

        tablaProductos.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tablaProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código Del Producto", "Descripción", "Cantidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaProductos.setComponentPopupMenu(menu_tabla);
        tablaProductos.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaProductos);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalles"));

        jLabel1.setText("Producto");

        jLabel3.setText("Cantidad");

        txtCantidad.setText("0");

        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(txtCantidad)
                        .addComponent(listProductos, 0, 178, Short.MAX_VALUE))
                    .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(listProductos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        btnGuardar.setText("Guardar Solicitud");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
        try {
            String[] fila = new String[3];
            /*
             * hacer metodo
             */
            String item = (String) listProductos.getSelectedItem();
            fila[0] = Consulta.getCodigoProducto(item);
            fila[1] = item;
            int cantidad = Integer.parseInt(txtCantidad.getText());
            fila[2] = "" + cantidad;
            if (item.equalsIgnoreCase("Seleccione un Producto") == false) {
                if (cantidad > 0) {
                    DefaultTableModel modelo = (DefaultTableModel) tablaProductos.getModel();
                    modelo.addRow(fila);
                    tablaProductos.setModel(modelo);
                } else {
                    javax.swing.JOptionPane.showMessageDialog(null, "Escriba la cantidad del producto", "Error", 1);
                }
            } else {
                javax.swing.JOptionPane.showMessageDialog(null, "Seleccione un producto", "Error", 1);
            }
        } catch (Exception e) {
            javax.swing.JOptionPane.showMessageDialog(null, "Ha ocurrido un error.\nComuniquese con su administrador de sistemas", "Error", 1);
        }
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void pop_eliminar_filaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pop_eliminar_filaActionPerformed
        // TODO add your handling code here:
        try {
            int fila = tablaProductos.getSelectedRow();
            DefaultTableModel modelo = (DefaultTableModel) tablaProductos.getModel();
            modelo.removeRow(fila);
            tablaProductos.setModel(modelo);
        } catch (Exception e) {
            javax.swing.JOptionPane.showMessageDialog(null, "No ha seleccionado ninguna fila", "Seleccione una fila", 1);
        }
    }//GEN-LAST:event_pop_eliminar_filaActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        int dependencia = Integer.valueOf(Consulta.userInSession.getDependencia().getCodigo());
        Calendar calendar = Calendar.getInstance();
        String date =String.valueOf(calendar.DATE).concat("/").concat(String.valueOf(calendar.MONTH).concat("/").concat(String.valueOf(calendar.YEAR)));
        String codigoSolicitud;
       if(tablaProductos.getRowCount()>0){
            Consulta.agregarSolicitud(dependencia,date ); 
            codigoSolicitud=Consulta.getSolicitud().get(Consulta.getSolicitud().size()-1).getCodigoSolicitud();
            for(int i=0;i<tablaProductos.getRowCount();i++){
                System.out.println(i);
                Consulta.agregarDetalleSolicitud(codigoSolicitud, tablaProductos.getValueAt(i, 0).toString(),Integer.parseInt(tablaProductos.getValueAt(i, 2).toString()));
            }
            javax.swing.JOptionPane.showMessageDialog(null, "Guardado !");
            txtCantidad.setText("");
            listProductos.setSelectedIndex(0);
            DefaultComboBoxModel cm = (DefaultComboBoxModel)listProductos.getModel();
       cm.removeAllElements();
        }else{
            javax.swing.JOptionPane.showMessageDialog(null, "No hay nada que guardar", "Ingrese datos", 1);
        }
        
    }//GEN-LAST:event_btnGuardarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JComboBox listProductos;
    private javax.swing.JPopupMenu menu_tabla;
    private javax.swing.JMenuItem pop_eliminar_fila;
    private javax.swing.JTable tablaProductos;
    private javax.swing.JTextField txtCantidad;
    // End of variables declaration//GEN-END:variables
}
